//
//  XMMeetSearchView.m
//  XMJJ_zmy
//
//  Created by 丁浩 on 2025/7/10.
//

#import "XMMeetSearchView.h"
#import "XMSearchHistoryView.h"
#import "XMHomeMeetCell.h"
#import "XMMeetAreaSelectView.h"

#define XMMEETSEARCHHISTORY        @"meetSearchHistoryKey"

@interface XMMeetSearchView ()<UITextFieldDelegate, UICollectionViewDelegate, UICollectionViewDataSource>

@property (nonatomic, strong) UITextField *searchTextField;

@property (nonatomic, strong) XMSearchHistoryView *searchHistoryView;

@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, strong) UIButton *allBtn;   //所有
@property (nonatomic, strong) UIButton *areaScreenBtn;  //地区选择
@property (nonatomic, strong) UIButton *priceSortBtn; //价格排序
@property (nonatomic, strong) UIImageView *upImgView; //价格增
@property (nonatomic, strong) UIImageView *downImgView; //价格降

@property (nonatomic, strong) XMMeetAreaSelectView *areaSelectView;

@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, strong) NSArray *areaModelArr;

@property (nonatomic, copy) NSString *isAscending; //价格排序 true 正序 false 倒序
@property (nonatomic, copy) NSString *city;

@end

@implementation XMMeetSearchView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self creatUI];
    }
    return self;
}

- (void)creatUI {
    [self addSubview:self.navView];
    self.navView.backgroundColor = kColorHEX(0xffffff);
    [self.navView addSubview:self.searchTextField];
    
    UIButton *searchBtn = [UIButton buttonWithType:UIButtonTypeCustom font:KFontSize(16.0) frame:CGRectMake(self.width - KScaleWidth(52.0), kNavagationBarH - 44, KScaleWidth(52.0), 44) title:@"搜索" titleColor:kColorHEX(0x333333)];
    [searchBtn addTarget:self action:@selector(searchAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.navView addSubview:searchBtn];
    
    [self addSubview:self.collectionView];
    [self addSubview:self.searchHistoryView];
    _collectionView.hidden = YES;
    _searchHistoryView.hidden = NO;
    [_searchHistoryView setContentWithHistoryKey:XMMEETSEARCHHISTORY];
    [self addSubview:self.allBtn];
    [self addSubview:self.areaScreenBtn];
    [self addSubview:self.priceSortBtn];
    [_priceSortBtn addSubview:self.upImgView];
    [_priceSortBtn addSubview:self.downImgView];
    [self bringSubviewToFront:self.searchHistoryView];
}

- (void)setContentWithProductModelArr:(NSArray *)productModelArr
                                 page:(NSInteger)page {
    _collectionView.hidden = NO;
    _searchHistoryView.hidden = YES;
    [_collectionView.mj_header endRefreshing];
    if (page == 1) {
        [self.dataArr removeAllObjects];
        [_searchHistoryView saveSearchHistoryWithSearchKey:_searchTextField.text];
    }
    if (productModelArr.count < 10) {
        [_collectionView.mj_footer endRefreshingWithNoMoreData];
    }
    else {
        [_collectionView.mj_footer endRefreshing];
    }
    [self.dataArr addObjectsFromArray:productModelArr];
    [_collectionView reloadData];
}

- (void)setAreaSelectInfoWithAreamodelArr:(NSArray *)areaModelArr {
    _areaModelArr = areaModelArr;
}

#pragma mark - BtnAction
- (void)searchAction:(UIButton *)button {
    [self endEditing:YES];
    if (_searchTextField.text.length > 0) {
        if (self.delegate && [self.delegate respondsToSelector:@selector(meetSearchWithSearchKey:isAscending:city:)]) {
            [self.delegate meetSearchWithSearchKey:_searchTextField.text
                                       isAscending:_isAscending
                                              city:_city];
        }
    }
    else {
        [MBProgressHUD showError:@"请输入搜索内容"];
    }
}

//全部
- (void)allSelectAction:(UIButton *)button {
    if (button.selected) {
        return;
    }
    button.selected = YES;
    _areaScreenBtn.selected = NO;
    [_areaScreenBtn setTitle:@"区域" forState:UIControlStateNormal];
    _city = @"";
    if (self.delegate && [self.delegate respondsToSelector:@selector(meetSearchWithSearchKey:isAscending:city:)]) {
        [self.delegate meetSearchWithSearchKey:_searchTextField.text
                                   isAscending:_isAscending
                                          city:_city];
    }
}

//区域选择
- (void)areaSelectAction:(UIButton *)button {
    if (_areaModelArr.count > 0) {
        [self addSubview:self.areaSelectView];
        [self.areaSelectView setContentWithAreaModelArr:self.areaModelArr];
    }
    else {
        if (self.delegate && [self.delegate respondsToSelector:@selector(areaSelectAction)]) {
            [self.delegate areaSelectAction];
        }
    }
}

//价格排序
- (void)priceSortAction:(UIButton *)button {
    button.selected = !button.selected;
    if (button.selected) {
        _isAscending = @"false";
        _upImgView.image = ImageNamed(@"price_sort_up_icon");
        _downImgView.image = ImageNamed(@"price_sort_down_icon_select");
    }
    else {
        _isAscending = @"true";
        _upImgView.image = ImageNamed(@"price_sort_up_icon_select");
        _downImgView.image = ImageNamed(@"price_sort_down_icon");
    }
    if (self.delegate && [self.delegate respondsToSelector:@selector(meetSearchWithSearchKey:isAscending:city:)]) {
        [self.delegate meetSearchWithSearchKey:_searchTextField.text
                                   isAscending:_isAscending
                                          city:_city];
    }
}

#pragma mark - Delegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArr.count;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat itemWidth = floor((self.width - KScaleWidth(8.0)*3)/2);
    ZMYCommend *zmyCommend = self.dataArr[indexPath.row];
    // 计算单行文本宽度
    NSString *text = zmyCommend.title;
    CGFloat height = [text getHeightWithFont:KScaleWidth(16.0) withWidth:itemWidth - KScaleWidth(10.0)*2] + KScaleWidth(10.0);
    return CGSizeMake(itemWidth, MAX(KScaleWidth(32.0), height) + KScaleWidth(210.0) + KScaleWidth(74.0));
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    XMHomeMeetCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"XMHomeMeetCellName" forIndexPath:indexPath];
    [cell setContentWithMeetModel:self.dataArr[indexPath.row]];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    ZMYCommend *commend  = self.dataArr[indexPath.row];
    if (self.delegate && [self.delegate respondsToSelector:@selector(checkDetailWithProdId:)]) {
        [self.delegate checkDetailWithProdId:commend.objectId];
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self searchAction:nil];
    return YES;
}

#pragma mark - Init
- (UITextField *)searchTextField {
    if (!_searchTextField) {
        _searchTextField = [[UITextField alloc] initWithFrame:CGRectMake(44, kNavagationBarH - 44 + (44 - KScaleWidth(36.0))/2, self.width - 44 - KScaleWidth(52.0), KScaleWidth(36.0))];
        _searchTextField.font = KFontSize(13.0);
        _searchTextField.returnKeyType = UIReturnKeySearch;
        _searchTextField.placeholder = @"搜索内容/用户";
        _searchTextField.delegate = self;
        _searchTextField.backgroundColor = kColorHEX(0xF6F6F6);
        [_searchTextField setCornerRadius:_searchTextField.height/2];
        
        UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScaleWidth(30.0), _searchTextField.height)];
        UIImageView *searchIcon = [[UIImageView alloc] initWithFrame:CGRectMake((leftView.width - KScaleWidth(14.0))/2, 0, KScaleWidth(14.0), _searchTextField.height)];
        searchIcon.contentMode = UIViewContentModeScaleAspectFit;
        searchIcon.image = ImageNamed(@"mine_search_icon");
        [leftView addSubview:searchIcon];
        _searchTextField.leftView = leftView;
        _searchTextField.leftViewMode = UITextFieldViewModeAlways;
    }
    return _searchTextField;
}

- (XMSearchHistoryView *)searchHistoryView {
    if (!_searchHistoryView) {
        _searchHistoryView = [[XMSearchHistoryView alloc] initWithFrame:CGRectMake(0, kNavagationBarH, self.width, KScaleWidth(140.0))];
        XMWeakSelf;
        _searchHistoryView.historyItemSelectBlock = ^(NSString * _Nonnull historyStr) {
            weakSelf.searchTextField.text = historyStr;
            if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(meetSearchWithSearchKey:isAscending:city:)]) {
                [weakSelf.delegate meetSearchWithSearchKey:historyStr
                                               isAscending:weakSelf.isAscending
                                                      city:weakSelf.city];
            }
        };
    }
    return _searchHistoryView;
}

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.minimumLineSpacing = KScaleWidth(8.0);
        layout.minimumInteritemSpacing = KScaleWidth(8.0);
        layout.sectionInset = UIEdgeInsetsMake(KScaleWidth(8.0), KScaleWidth(8.0), KScaleWidth(8.0), KScaleWidth(8.0));
        
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, kNavagationBarH + KScaleWidth(47.0), self.width, self.height - kNavagationBarH - KScaleWidth(47.0)) collectionViewLayout:layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = kColorHEX(0xF6F6F6);
        [_collectionView registerClass:[XMHomeMeetCell class] forCellWithReuseIdentifier:@"XMHomeMeetCellName"];
        XMWeakSelf;
        _collectionView.mj_header = [MJRefreshStateHeader headerWithRefreshingBlock:^{
            if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(refreshData)]) {
                [weakSelf.delegate refreshData];
            }
        }];
        _collectionView.mj_footer = [MJRefreshAutoStateFooter footerWithRefreshingBlock:^{
            if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(loadMore)]) {
                [weakSelf.delegate loadMore];
            }
        }];
    }
    return _collectionView;
}

- (UIButton *)allBtn {
    if (!_allBtn) {
        _allBtn = [UIButton buttonWithType:UIButtonTypeCustom font:KFontSize(16.0) frame:CGRectMake(0, kNavagationBarH, self.width/3, KScaleWidth(47.0)) title:@"全部" selectTitle:@"全部" titleColor:kColorHEX(0x666666) selectColor:kColorHEX(0x333333)];
        _allBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [_allBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, KScaleWidth(20.0), 0, 0)];
        [_allBtn addTarget:self action:@selector(allSelectAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _allBtn;
}

- (UIButton *)areaScreenBtn {
    if (!_areaScreenBtn) {
        _areaScreenBtn = [UIButton buttonWithType:UIButtonTypeCustom font:KFontSize(16.0) frame:CGRectMake(self.width/3, kNavagationBarH, self.width/3, self.allBtn.height) title:@"区域" titleColor:kColorHEX(0x333333)];
        [_areaScreenBtn addTarget:self action:@selector(areaSelectAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _areaScreenBtn;
}

- (UIButton *)priceSortBtn {
    if (!_priceSortBtn) {
        _priceSortBtn = [UIButton buttonWithType:UIButtonTypeCustom font:KFontSize(16.0) frame:CGRectMake(self.areaScreenBtn.maxX, _areaScreenBtn.y, _areaScreenBtn.width, _areaScreenBtn.height) title:@"价格" titleColor:kColorHEX(0x666666)];
        [_priceSortBtn addTarget:self action:@selector(priceSortAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _priceSortBtn;
}

- (UIImageView *)upImgView {
    if (!_upImgView) {
        _upImgView = [[UIImageView alloc] initWithFrame:CGRectMake(self.priceSortBtn.width/2 + KScaleWidth(32.0)/2 + KScaleWidth(5.0), 0 - KScaleWidth(5.0)/2 - 2, KScaleWidth(8.0), _priceSortBtn.height)];
        _upImgView.contentMode = UIViewContentModeScaleAspectFit;
        _upImgView.image = ImageNamed(@"price_sort_up_icon");
    }
    return _upImgView;
}

- (UIImageView *)downImgView {
    if (!_downImgView) {
        _downImgView = [[UIImageView alloc] initWithFrame:CGRectMake(self.upImgView.x, KScaleWidth(5.0)/2 + 2, KScaleWidth(8.0), _upImgView.height)];
        _downImgView.contentMode = UIViewContentModeScaleAspectFit;
        _downImgView.image = ImageNamed(@"price_sort_down_icon");
    }
    return _downImgView;
}

- (XMMeetAreaSelectView *)areaSelectView {
    if (!_areaSelectView) {
        _areaSelectView = [[XMMeetAreaSelectView alloc] initWithFrame:CGRectMake(0, kNavagationBarH + KScaleWidth(47.0), self.width, self.height - kNavagationBarH - KScaleWidth(47.0))];
        XMWeakSelf;
        _areaSelectView.areaSelectBlock = ^(NSString * _Nonnull areaStr) {
            weakSelf.city = [[areaStr componentsSeparatedByString:@"-"] objectAtIndex:1];
            [weakSelf searchAction:nil];
        };
    }
    return _areaSelectView;
}

- (NSMutableArray *)dataArr {
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
